import {
  DndContext,
  closestCenter,
  MouseSensor,
  useSensor,
  useSensors,
  DragEndEvent
} from '@dnd-kit/core';
import {
  SortableContext,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable';

import { FC } from 'react';

type SortDndContext_PropsType = {
  children: JSX.Element | JSX.Element[],
  items: Array<{id:string,[key:string]:any}>,
  ondrag: (oldIndex: number, newIndex: number) => void
}

const SortDndContext: FC<SortDndContext_PropsType> = (props) => {
  const { items, ondrag,children } = props
  const sensors = useSensors(
    useSensor(MouseSensor,{
      activationConstraint:{
        distance:9
      }
    }),
  );
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (!over) return
    if (active.id !== over.id) {
      const oldIndex = items.findIndex(c => c.fe_id === active.id);
      const newIndex = items.findIndex(c => c.fe_id === over.id);
      ondrag(oldIndex, newIndex)
    }
  }


  return <DndContext
    sensors={sensors}
    collisionDetection={closestCenter}
    onDragEnd={handleDragEnd}
  >
    <SortableContext
      items={items}
      strategy={verticalListSortingStrategy}
    >
      {children}
    </SortableContext>
  </DndContext>
}


export default SortDndContext